<?php

namespace App\Http\Middleware;
use App;
use \App\Http\Controllers\CurlTrait;
use \App\Http\Controllers\WechatService;
use App\Repositories\UserRepository;
use App\User;
use Auth;
use App\Configuration;
use Closure;
use Illuminate\Http;
use Illuminate\Http\Request;
use Session;
use Illuminate\Support\Facades\Hash;


class RedirectIfAuthenticated
{
    use CurlTrait;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        //Auth::loginUsingId(1);
        $allLanguage = $request->header('accept-language');
            $language = explode(',',$allLanguage);
            switch($language[0])
            {
                case 'zh':
                    App::setLocale('zh');
                    break;
                case 'zh-CN':
                    App::setLocale('zh');
                    break;
                case 'en':
                    App::setLocale('en');
                    break;
                case 'en-US':
                    App::setLocale('en');
                    break;
                default:
                    App::setLocale('en');
            }
        if (!preg_match('/MicroMessenger/', $_SERVER['HTTP_USER_AGENT'] ) && config('app.debug')) {
            return $next($request);
            
        } else {
            $request->session()->put('wechat', true);
        }
        //if (!Auth::guard($guard)->check()) {
            $state = $request->input('state', 'register');
            $user_info = $request->session()->get('user_info');
            $wechat_config = \App::make('config')->get('services.wechat', []);
            extract($wechat_config);
            $wx = new WechatService();
            $baseToken = $wx->getToken();
            if (!empty($user_info)) {
                //auto login
                $userId = $this->loginUser($user_info);
                if($userId == -1) {
                    $request->session()->put('port_refuse', true);
                } else{
                    $request->session()->put('port_refuse', false);
                }
                return $next($request);
            }

            $code = $request->input('code', '');
            //first access
            if (empty($code)) {
                $redirect_uri = url('/').'?state='.$state;
                $redirectUrl = urlencode($redirect_uri);
                header('location: https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirectUrl.'&response_type=code&scope=snsapi_userinfo&state='.$state.'#wechat_redirect');
                exit;
            } else {
                $returned = $this->getWechatAPIAccessToken($request);
                if (!isset($returned['access_token']) || !isset($returned['openid'])) {
                    dd('what is going on?');
                }

                $returnedJson = array(
                    'openid' => $returned['openid'],
                    'access_token' => $baseToken
                );
                $userInfo = $this->getWechatAPIUserInfo($request, $returnedJson);
                if (!isset($userInfo['openid'])) {
                    dd('no user openid found');
                }
                $request->session()->put('user_info', $userInfo);
                $userId = $this->loginUser($userInfo);
                if($userId == -1) {
                    $request->session()->put('port_refuse', true);
                } else{
                    $request->session()->put('port_refuse', false);
                }
            }
        //}
        return $next($request);
    }
    
    public function setDefaultLanguage(Request $request, $language) {
      if ($language == 'zh_CN') {
        $language = 'zh';
      } else {
        $language = 'en';
      }
      $request->session()->put('language', $language);
      App::setLocale($language);
    }
    
    //private functions   
    private function getWechatAPIAccessToken(Request $request) {
      $code = $request->input('code');
      $state = $request->input('state');
      
      $wechat_config = \App::make('config')->get('services.wechat', []);
      extract($wechat_config);
      
      $grantType = 'authorization_code';
      $lang = env('WECHAT_DEFAULTLANG');
      $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=$grantType";
      $json = $this->curlCallGet($url);
      return json_decode($json,true);
    }
    
    private function getWechatAPIUserInfo(Request $request, $returnedJson) {
      $accessToken = $returnedJson['access_token'];
      $openid = $returnedJson['openid'];
      $lang = env('WECHAT_DEFAULTLANG');
      $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$accessToken&openid=$openid&lang=zh_CN";
      //$url ="https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$openid&lang=$lang";
      $json = $this->curlCallGet($url);
      return json_decode($json, true);
    }

    private function loginUser($userInfo) {
      $repo = new UserRepository();
      $user = $repo->getByOpenId($userInfo['openid']);
      if (empty($user)) {
        $userId = 0;
      } else {
        $userId = $user->id;
          $sugar = new \Spinegar\Sugar7Wrapper\Rest();
          $config = \App::make('config')->get('services.stm');
          extract($config);
          $sugar->setUrl($hosturl)
              ->setUsername($username)
              ->setPassword($password)
              ->setPlatform($platform)
              ->connect();

          $contacts = $sugar->filter('Contacts', array(
              'filter' => array(
                  array('open_id_c' => $userInfo['openid'])
              )
          ));
          if(count($contacts['records'])){
              $records = $contacts['records'][0];
              if($records['is_portal_user_c'] != 1) {
                  $userId = -1;
              } else {
                  $user->name = $records['wechat_name_c'];
                  $user->gender = $records['gender_c'];
                  $user->mobile_phone = $records['phone_work'];
                  $user->city = $records['city_c'];
                  $user->region = $records['region_c'];
                  $user->is_contact == 1;
                  $user->save();
              }
          } else {
              if ($user->is_contact == 0) {
                  $userId = -1;
              }
          }
      }

      //sync sugarcrm Contact to User, using $userInfo['openid']
      //User::update(Contact);
      
      if ($userId > 0) {
        Auth::loginUsingId($userId, true);
      }
      return $userId;
    }
}
